package com.lin.operatorlogrecord.content;

import com.lin.operatorlogrecord.unit.OperatorLogUtil;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: chenghao.lin
 * @Date: 2023/09/25
 * @Description: 新增对象内容生成器
 */
public class ObjectAddLogUtil {

    public String generatorContent(Object object, String objectType) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        // 获取操作数据元数据
        OperatorLogMetaDataBuilder builder = new OperatorLogMetaDataBuilder();
        OperatorLogMetaData metaData = builder.getChangeModel(object, object.getClass());
        // 生成新增字段
        List<OperatorLogRecord> filedContents = listFiledContent(metaData);
        // 排序，并转为String
        String content = OperatorLogUtil.sortOperatorLogRecord(filedContents);
        return OperatorLogContentUtil.addObjFormat(metaData.getName(), objectType, content);
    }

    /**
     * 生成字段变更内容
     * @param metaData
     * @return
     */
    private List<OperatorLogRecord> listFiledContent(OperatorLogMetaData metaData) {
        List<OperatorLogRecord> result = new ArrayList<>();
        Map<String, String> fieldMap = metaData.getFieldMap();
        Map<String, Integer> filedNameAndPriorityMap = metaData.getFiledNameAndPriorityMap();
        for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
            // 新增成员
            String fieldContent = OperatorLogContentUtil.addFiledFormat(entry.getKey(), entry.getValue());
            OperatorLogRecord record = new OperatorLogRecord(filedNameAndPriorityMap.get(entry.getKey()), fieldContent);
            result.add(record);
        }
        return result;
    }

}
